import React from 'react';
import { Typography } from 'antd';
import { Bar } from '@ant-design/plots';
import analysedData from './result.json';

const { Title } = Typography;

export default props => {
    const { title, attr = 'damage' } = props;
    const getValue = item => {
        if (typeof attr === 'string') {
            return item[attr];
        } else {
            return attr(item)
        }
    }

    const getSum = (list) => {
        return list.reduce((pre, cur) => pre + getValue(cur), 0);
    }

    const data = [];
    Object.keys(analysedData.players).sort((a, b) => {
        return getSum(analysedData.players[b]) - getSum(analysedData.players[a]);
    }).map(name => {
        data.push(...analysedData.players[name].map((item, index) => ({
            ...item,
            index: index + 1,
            _attr: getValue(item),
        })));
    });

    return (
        <div className="plot-card">
            <Title level={5}>{title}</Title>
            <Bar
                autoFit={false}
                height={200}
                legend={false}
                data={data}
                xField="_attr"
                yField="name"
                isGroup
                isStack
                seriesField="index"
                groupField="name"
                barWidthRatio={2}
                interactions={[{
                    type: 'element-highlight-by-color',
                }, {
                    type: 'element-link',
                }]}
                connectedArea={{
                    style: (oldStyle, element) => {
                        return {
                            fill: 'rgba(0,0,0,0.25)',
                            stroke: oldStyle.fill,
                            lineWidth: 0.5,
                        };
                    },
                }}
                tooltip={false}
                label={{
                    position: 'middle',
                    layout: [{
                        type: 'interval-adjust-position',
                    }, {
                        type: 'interval-hide-overlap',
                    }, {
                        type: 'adjust-color',
                    }],
                }}
            />
        </div>
    );
};